package br.com.agregador.persistencia.daoimpl;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import br.com.agregador.entity.Consumidor;
import br.com.agregador.persistencia.dao.ConsumidorDAO;

@Repository("consumidorDAO")
public class ConsumidorDAOImpl implements ConsumidorDAO {
	
	private static final long serialVersionUID = 1L;
	
	@PersistenceContext
	private EntityManager entityManager;	

	@Override
	public void salvar(Consumidor consumidor) {		
		entityManager.persist(consumidor);
	}

	@Override
	public Consumidor recuperarConsumidor(String email) {
		StringBuilder sb = new StringBuilder("from Consumidor c ");
		sb.append("left outer join fetch c.perfis ");
		sb.append("where c.email = '"+email+"'");
		Query query = entityManager.createQuery(sb.toString());
		Consumidor consumidor = null;
		try {
			consumidor = (Consumidor) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		} catch (EntityNotFoundException e){
			return null;
		}
		return consumidor;
	}

	@Override
	public void excluir(Consumidor consumidor) {
		entityManager.remove(consumidor);		
	}

	@Override
	public Consumidor recuperarConsumidor(Integer id) {
		StringBuilder sb = new StringBuilder("from Consumidor c ");
		sb.append("left outer join fetch c.perfis ");
		sb.append("left outer join fetch c.cidades ");
		sb.append("left outer join fetch c.categorias ");
		sb.append("where c.id = "+id);
		Query query = entityManager.createQuery(sb.toString());
		Consumidor consumidor = null;
		try {
			consumidor = (Consumidor) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		} catch (EntityNotFoundException e){
			return null;
		}
		return consumidor;
	}

	@Override
	public void atualizar(Consumidor consumidor) {
		entityManager.merge(consumidor);
	}
}
